import base64
import hashlib
import hmac
import json
import re
import time
import urllib.parse

import requests

from FasterRunner.settings import DINGDING_ACCESS_TOKEN, DINGDING_SECRET


def dd_alert(runresult):
    """
    doc:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
    :param text:
    :return:
    """
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    timestamp = str(round(time.time() * 1000))
    secret = DINGDING_SECRET
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    api_url = "https://oapi.dingtalk.com/robot/send?access_token={access_token}&timestamp={timestamp}&sign={sign}".format(access_token=DINGDING_ACCESS_TOKEN, timestamp=timestamp,
                                                                                                                          sign=sign)
    tests = runresult.get("tests")
    links = []
    for test in tests:
        messageURL = test.get('link')
        matchObj = re.match(r'<a href=(.*?)>', messageURL, re.M | re.I)
        link = matchObj.group(1)
        picURL = "http://api.test.thinkinpower.net/static/images/Fail.jpg"
        if test['status'] == "success":
            picURL = "http://api.test.thinkinpower.net/static/images/Pass.jpg"
        else:
            picURL = "http://api.test.thinkinpower.net/static/images/Fail.jpg"
        links.append({"title": "执行结果:" + test['status'] + "！;任务名称:" + test['name'], "messageURL": link, "picURL": picURL})
    content = {
        "feedCard": {
            "links": links
        },
        "msgtype": "feedCard"
    }
    resp = requests.post(api_url, json.dumps(content), headers=headers, verify=False)
    print("钉钉发送结果：", resp.content)
